import express from "express"

import { getUsers, getUserById, deleteUserById } from "../db/users"

export const getAllUsers = async (req: express.Request, res: express.Response) => {
  try {
    const users = await getUsers()

    return res.status(200).json({ message: 'Users found', users }).end()
    
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}

export const deleteUser = async (req: express.Request, res: express.Response) => {
  try {
    const { id } = req.params

    if (!id) return res.sendStatus(400)

    const user = await getUserById(id)

    if (!user) return res.sendStatus(400)

    const deletedUser = await deleteUserById(id)

    return res.status(200).json({ message: 'User deleted', deletedUser }).end()
    
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}

export const updateUserbyId = async (req: express.Request, res: express.Response) => {
  try {
    const { id } = req.params
    const { username } = req.body

    if (!id) return res.sendStatus(400)

    const user = await getUserById(id)

    if (!user) return res.sendStatus(400)

    // const updatedUser = await updateUserById(id, req.body)
    user.username = username
    const updatedUser = await user.save()
    
    return res.status(200).json({ message: 'User updated', updatedUser }).end()
    
  } catch (error) {
    console.log(error)
    return res.sendStatus(400)
  }
}
